namespace ClassyBlog.Infrastructure
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Reflection;
    using System.Web.Compilation;
    using System.Web.Hosting;

    public class DefaultBuildManager : IBuildManager
    {
        private IEnumerable<Assembly> privateAssemblies;

        public virtual IEnumerable<Assembly> PrivateAssemblies
        {
            [DebuggerStepThrough]
            get
            {
                if (IsRunningInWebEnvironment)
                {
                    return privateAssemblies ?? (privateAssemblies = BuildManager.GetReferencedAssemblies()
                                                                                 .Cast<Assembly>()
                                                                                 .Where(assembly => !assembly.GlobalAssemblyCache)
                                                                                 .ToList());
                }

                return Enumerable.Empty<Assembly>();
            }
        }

        private static bool IsRunningInWebEnvironment
        {
            [DebuggerStepThrough]
            get { return HostingEnvironment.IsHosted; }
        }

        [DebuggerStepThrough]
        public virtual bool FileExists(string virtualPath)
        {
            return IsRunningInWebEnvironment &&
                   BuildManager.GetObjectFactory(virtualPath, false) != null;
        }

        [DebuggerStepThrough]
        public virtual Type GetCompiledType(string virtualPath)
        {
            return IsRunningInWebEnvironment ?
                   BuildManager.GetCompiledType(virtualPath) : null;
        }
    }
}